package cn.dglydrpy.study.j2ee.servlet.day12;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.dglydrpy.study.j2ee.manage.dao.UserDAO;
import cn.dglydrpy.study.j2ee.manage.entity.User;

/* 
 * 将所有需要用到的jsp放入WEB-INF 隐藏jsp,让用户不能直接访问jsp 改动所有相应的跳转地址
 */
public class ActionServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取请求资源路径：
		String URL = request.getRequestURI();
		System.out.println(URL);

		//截取
		String path = URL.substring(URL.lastIndexOf("/"),URL.lastIndexOf("."));
		System.out.println(path);

		//依据请求路径，进行对应的处理：
		if("/login".equals(path)){
			processLogin(request, response);
		}else if("/listUser".equals(path)){
			processListUser(request, response);
		}else if ("/addUser".equals(path)) {
			processAddUser(request, response);
		}else if("/delUser".equals(path)){
		processDelUser(request, response);
		}else if("/toAdd".equals(path)){
			request.getRequestDispatcher("/WEB-INF/addUser.jsp").forward(request, response);
		}else if("/toList".equals(path)){
			request.getRequestDispatcher("/WEB-INF/listUser.jsp").forward(request, response);
		}else if("/toLogin".equals(path)){
			request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
		}
	}
	private void processLogin(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("name").trim();
		String pwd = request.getParameter("pwd").trim();

		UserDAO dao = new UserDAO();
		try{
			User user = dao.findByUsername(name);
			if(user.getUsername()==null){
				request.setAttribute("msg", "用户不存在,请重新登录！");
				request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
			}else if(user.getPassword().equals(pwd)){
				/*
				 * 登录成功，在session对象上绑定一些数据，为session验证做准备
				 */
				System.out.println("用户登录成功！");
				HttpSession session = request.getSession();
				session.setAttribute("user", user);

				response.sendRedirect("listUser.do");
			}else{
				request.setAttribute("msg", "密码不正确,请重新登录！");
				request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
			}
		}catch(Exception e){
			request.setAttribute("msg", "系统繁忙，请稍后重试");
			request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
		}
	}
	private void processAddUser(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		/*
		 * 对浏览器端提交过来的数据使用
		 * 指定的字符集来解码。
		 * 注:
		 * 	这行代码要添加到所有的getParameter方法的前面。
		 * 	只针对post请求有效。
		 */


		request.setCharacterEncoding("UTF-8"); 
		//读取用户信息
		User user = new User();

		user.setUsername(request.getParameter("username"));
		user.setPassword(request.getParameter("password"));
		user.setEmail(request.getParameter("email"));
		user.setPhone(request.getParameter("phone"));
		/*
		 * 1.设置Content-type消息头，告诉浏览器服务器返回的数据类型及编码
		 * 2.设置Out在输出时，使用哪种字符集来编码
		 */
		//输出流交给jsp

		//提交的信息保存到数据库
		UserDAO dao = new UserDAO();
		try{
			dao.save(user);
			/*
			 * out在输出时，默认会使用iso-8859-1
			 * 来编码。
			 */

			response.sendRedirect("listUser.do");//先把response对象的数据清空，再重定向信息放到response 等下面的代码执行完立即重定向；重定向网址可以放绝对网址和相对网址

		} catch (Exception e){
			e.printStackTrace();
			request.setAttribute("msg", "用户名不可重复，注册失败！");
			request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request,response);
		}
	}
	private void processDelUser(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		
		UserDAO dao = new UserDAO();
		try{
			dao.deleteById(Integer.parseInt(request.getParameter("id").trim()));
			response.sendRedirect("listUser.do");
		} catch(Exception e){
			e.printStackTrace();
			request.setAttribute("msg", "系统繁忙，稍后再试！");
			request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
		}
	}
	private void processListUser(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		
		try {
			UserDAO dao = new UserDAO();
			List<User> users = dao.findAll();
			//1.绑定数据到request
			request.setAttribute("users", users);
			//2.获得转发器
			RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/listUser.jsp");
			//3.转发
			rd.forward(request, response);

		} catch (Exception e) {
			e.printStackTrace();
			//转发到异常页面
			request.setAttribute("msg", "系统繁忙，稍后重试！");
			request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
		}
	}
}
